package com.sky.aspect;

import com.sky.annotation.AutoAnnotation;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.beans.beancontext.BeanContext;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Slf4j
@Aspect
public class AutoAspect {
    //切入点
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoAnnotation)")
    public void autoAspectPointcut() {
    }
    //前置通知
    @Before("autoAspectPointcut()")
    public void autoFill(JoinPoint joinPoint) {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取方法对象后，获取方法上标注的注解对象
        AutoAnnotation annotation = signature.getMethod().getAnnotation(AutoAnnotation.class);
        OperationType value = annotation.value();// 获取属性值

        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        // 获取第一个元素
        Object arg = args[0];
        LocalDateTime now = LocalDateTime.now();
        Long id = BaseContext.getCurrentId();
        // 判断 OperationType 类型
        if (value == OperationType.INSERT) {
            try {
                Method creat_method = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method create_user_method = arg.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method update_method = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method update_user_method = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                creat_method.invoke(arg, now);
                create_user_method.invoke(arg, id);
                update_method.invoke(arg, now);
                update_user_method.invoke(arg, id);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                Method update_method = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method update_user_method = arg.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                update_method.invoke(arg, now);
                update_user_method.invoke(arg, id);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
